
#include <cstdio>
#include <iostream>
#include <boost/filesystem.hpp>

#include "Ktrace.hpp"

using namespace Ktracens;

Ktrace::Ktrace(Options const & options) : 
	_options(options)
{

}

Ktrace::~Ktrace()
{

}

void Ktrace::run()
{
	if (this->_checkOutfile())
	{
		if (this->_options.exists("command"))
			this->_forkCommand();
	}
}

void Ktrace::_forkCommand()
{
	int pid = fork();
	if (pid == 0)
		this->_pid = getppid();
	else
	{
		char** command = this->_buildCommandFromOptions();
		if (command)
		{
			int ret = execv(command[0], command);
			if (ret != 0)
				std::cout << "exec failed: " << strerror(errno) << std::endl;
		}
	}	
}

char** Ktrace::_buildCommandFromOptions() const
{
	char** cmd;
	std::vector<std::string> const & cmd_vec = this->_options.get<std::vector<std::string> >("command");
	cmd = new char*[cmd_vec.size()];
	std::vector<std::string>::const_iterator ite = cmd_vec.end();
	int i = 0;
	for (std::vector<std::string>::const_iterator it = cmd_vec.begin(); it != ite; it++)
	{
		cmd[i] = strdup(it->c_str());
		i++;
	}
	cmd[i] = NULL;
	return cmd;
}

bool Ktrace::_checkOutfile() const
{
	std::string const & path = this->_options.get<std::string>("outfile");
	char mode[2] = "w";
	if (this->_options.exists("append"))
		mode[0] = 'a';	
	FILE* file = fopen(path.c_str(), mode);
	if (file == NULL)
	{
		std::cout << "Couldn't create " << path << ": " << strerror(errno) << std::endl;
		return false;
	}
	fclose(file);
	return true;
}

